package com.activemq.utils;

import com.activemq.entity.UserDto;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

public class XmlUtils {

	@SuppressWarnings("rawtypes")
	public static Map<String, Object> Dom2Map(String xml) throws DocumentException{ 
        Map<String, Object> map = new HashMap<String, Object>(); 
        
        Document doc=DocumentHelper.parseText(xml);
        
        if(doc == null) 
            return map; 
        Element root = doc.getRootElement(); 
        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) { 
            Element e = (Element) iterator.next(); 
            List list = e.elements(); 
            if(list.size() > 0){ 
                map.put(e.getName(), Dom2Map(e)); 
            }else 
                map.put(e.getName(), e.getText()); 
        } 
        return map; 
    }
	
	@SuppressWarnings("rawtypes")
	public static List<Map<String,Object>> Dom2Maps(String xml) throws DocumentException
	{
		Document doc=DocumentHelper.parseText(xml);
		List<Map<String,Object>> maps=new ArrayList<Map<String,Object>>();
        if(doc == null) 
        {
        	return maps; 
        }
        
        Map<String,Object> map=null;
        Element root = doc.getRootElement(); 
        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) { 
        	map=new HashMap<String,Object>();
            Element e = (Element) iterator.next(); 
            List list = e.elements(); 
            if(list.size() > 0){ 
                map.put(e.getName(), Dom2Map(e)); 
            }else{
            	map.put(e.getName(), e.getText()); 
            }
            maps.add(map);
        } 
        return maps;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map Dom2Map(Element e){ 
        Map map = new HashMap(); 
        List list = e.elements(); 
        if(list.size() > 0){ 
            for (int i = 0;i < list.size(); i++) { 
                Element iter = (Element) list.get(i); 
                List mapList = new ArrayList(); 
                 
                if(iter.elements().size() > 0){ 
                    Map m = Dom2Map(iter); 
                    if(map.get(iter.getName()) != null){ 
                        Object obj = map.get(iter.getName()); 
                        if(!obj.getClass().getName().equals("java.util.ArrayList")){ 
                            mapList = new ArrayList(); 
                            mapList.add(obj); 
                            mapList.add(m); 
                        } 
                        if(obj.getClass().getName().equals("java.util.ArrayList")){ 
                            mapList = (List) obj; 
                            mapList.add(m); 
                        } 
                        map.put(iter.getName(), mapList); 
                    }else 
                        map.put(iter.getName(), m); 
                } 
                else{ 
                    if(map.get(iter.getName()) != null){ 
                        Object obj = map.get(iter.getName()); 
                        if(!obj.getClass().getName().equals("java.util.ArrayList")){ 
                            mapList = new ArrayList(); 
                            mapList.add(obj); 
                            mapList.add(iter.getText()); 
                        } 
                        if(obj.getClass().getName().equals("java.util.ArrayList")){ 
                            mapList = (List) obj; 
                            mapList.add(iter.getText()); 
                        } 
                        map.put(iter.getName(), mapList); 
                    }else 
                        map.put(iter.getName(), iter.getText()); 
                } 
            } 
        }else 
            map.put(e.getName(), e.getText()); 
        return map; 
    }

    public static <T> T fromXml(String xml, Class<T> clazz) {
        try {
            xml = xml.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
            XStream xstream = null;
            if (xml.indexOf("xmlns:xsi") == -1) {
                xstream = new XStream(new DomDriver("UTF-8"));
            } else {
                xstream = new XStream(new StaxDriver());
            }

            xstream.processAnnotations(clazz);
            T obj = (T) xstream.fromXML(xml);
            return obj;
        } catch (Exception var4) {
            var4.printStackTrace();
            return null;
        }
    }

	public static void main(String[] args) {
//		String xml="<ChemicalBaseInfos><ChemicalBaseInfo><id>402884f75b55bab2015b55c069620000</id><cnName>二乙基甲酰胺</cnName><cnAlias>N,N-二乙基甲酰胺</cnAlias><enName>N,N-diethylformamide</enName><dangerNo>无资料</dangerNo><casNo>617-84-5</casNo><unNo>无资料</unNo><danger>遇明火、高热或与氧化剂接触，有引起燃烧爆炸的危险。</danger><purpose>用作防腐剂、驱虫剂、溶剂等。</purpose><packaging>无资料。</packaging><healthHazard>侵入途径：吸入,食入,经皮吸收。&lt;br&gt;健康危害：吸入、摄入或经皮肤吸收对身体有害。对眼和皮肤有刺激性，可致接触性荨麻疹。</healthHazard><chemicalType>0601000003</chemicalType><categoryId>402884f75b55b0b3015b55b42d600001</categoryId><ChemicalCategory><id>402884f75b55b0b3015b55b42d600001</id><categoryName>爆炸品</categoryName><parent><id>402884f75b55b0b3015b55b375f20000</id><categoryName>危险化学品分类菜单</categoryName></parent></ChemicalCategory><ChemicalAddThings><ChemicalAddThing><id>402884f75c62464e015c62490b290003</id><thingName>氨基酸</thingName><casNo>A001</casNo><character>1</character><content>1</content><effect>1</effect></ChemicalAddThing></ChemicalAddThings><ChemicalByproducts><ChemicalByproduct><id>402884f75c62464e015c6247ce8d0000</id><byproductName>副1</byproductName><casNo>F001</casNo><molecularWeight>1</molecularWeight></ChemicalByproduct></ChemicalByproducts><ChemicalCharacteristics><ChemicalCharacteristic><id>402884f75b5b5871015b5b5e3fa80000</id><item>0602000001</item><result>偏高</result></ChemicalCharacteristic><ChemicalCharacteristic><id>402884f75b65d3b8015b65d4f1040000</id><item>0602000002</item><result>偏高</result></ChemicalCharacteristic></ChemicalCharacteristics><ChemicalEmergencyMeasuress><ChemicalEmergencyMeasures><id>402884f75c62464e015c6249d49c0006</id><emergencyType>0607000001</emergencyType><content>解毒</content></ChemicalEmergencyMeasures></ChemicalEmergencyMeasuress><ChemicalEnvironmentStandards><ChemicalEnvironmentStandard><id>402884f75c62464e015c624a467c0007</id><standardItem>环标001</standardItem><unit>长天</unit><standardArea>1000-1200</standardArea></ChemicalEnvironmentStandard></ChemicalEnvironmentStandards><ChemicalForbidThings><ChemicalForbidThing><id>402884f75c62464e015c62484d970001</id><thingName>禁001</thingName><casNo>J001</casNo><consequences>严重</consequences></ChemicalForbidThing></ChemicalForbidThings><ChemicalImpuritiess><ChemicalImpurities><id>402884f75c62464e015c6248a40b0002</id><impuritiesName>杂001</impuritiesName><casNo>Z001</casNo><molecularWeight>1</molecularWeight><maxContent>5</maxContent></ChemicalImpurities></ChemicalImpuritiess><ChemicalMonitorMethods><ChemicalMonitorMethod><id>402884f75c62464e015c624a9a6e0008</id><methodName>观测</methodName><isFastMethod>0</isFastMethod><standardNo>G001</standardNo><range>100000</range><remark></remark></ChemicalMonitorMethod></ChemicalMonitorMethods><ChemicalSafeMeasuress><ChemicalSafeMeasures><id>402884f75c62464e015c62498e100005</id><safeType>0606000001</safeType><content>防护监测</content></ChemicalSafeMeasures></ChemicalSafeMeasuress><ChemicalToxicologicals><ChemicalToxicological><id>402884f75c62464e015c62494b7b0004</id><toxicologicalName>0604000001</toxicologicalName><result>脸色发黑，呕吐</result></ChemicalToxicological></ChemicalToxicologicals><ChemicalNoteMatters><id>402884f75b5b6834015b5b7be1880000</id><operationMatters>111</operationMatters><storageMatters>222</storageMatters><transportationMatters>333</transportationMatters><remark>444</remark></ChemicalNoteMatters></ChemicalBaseInfo><ChemicalBaseInfo><id>402884f75c7b3ed7015c7b4189ac0000</id><cnName>二氧化碳</cnName><cnAlias>二氧化碳</cnAlias><enName>CO2</enName><enAlias>CO2</enAlias><dangerNo>1524-1</dangerNo><casNo>C120</casNo><stability>一般</stability><chemicalType>0601000003</chemicalType><categoryId>402884f75b55b0b3015b55b462cb0002</categoryId><ChemicalCategory><id>402884f75b55b0b3015b55b462cb0002</id><categoryName>气体</categoryName><parent><id>402884f75b55b0b3015b55b375f20000</id><categoryName>危险化学品分类菜单</categoryName></parent></ChemicalCategory><ChemicalCharacteristics><ChemicalCharacteristic><id>402884f75c7b3ed7015c7b50b02d0001</id><item>0602000003</item><result>超标</result></ChemicalCharacteristic></ChemicalCharacteristics><ChemicalNoteMatters><id>402884f75c7b3ed7015c7b51009a0002</id><operationMatters>C0001</operationMatters><storageMatters>C0002</storageMatters><transportationMatters>C0003</transportationMatters><remark>C0004</remark></ChemicalNoteMatters></ChemicalBaseInfo></ChemicalBaseInfos>";
		//行政区划
		String xml="<user>\n" +
                "  <createDate>2022-06-06 07:02:37.0 UTC</createDate>\n" +
                "  <id>297e45618137d097018137d2d46e0002</id>\n" +
                "  <isConsole>1</isConsole>\n" +
                "  <syncType>2</syncType>\n" +
                "  <infoValid>1</infoValid>\n" +
                "  <mobile></mobile>\n" +
                "  <pwdLastedTime>2022-06-06 07:02:52.768 UTC</pwdLastedTime>\n" +
                "  <trueName>ererereee</trueName>\n" +
                "  <describe></describe>\n" +
                "  <email></email>\n" +
                "  <idCard></idCard>\n" +
                "  <password>810a1e042bcc1bece33588736e69263d58f3813ba26d6596ad462eba05969505</password>\n" +
                "  <updateTime>2022-06-06 07:02:52.781 UTC</updateTime>\n" +
                "  <status>1</status>\n" +
                "  <username>dfdfdfd</username>\n" +
                "  <smsValid>1</smsValid>\n" +
                "  <updatePlatformCode>1000</updatePlatformCode>\n" +
                "  <createPlatformCode>1000</createPlatformCode>\n" +
                "  <rootRegionCode>0</rootRegionCode>\n" +
                "</user>";

        UserDto list=fromXml(xml, UserDto.class);
        System.out.println("数量："+list.getCreateDate());
//		try {
//			List<Map<String,Object>> list=Dom2Maps(xml);
//			System.out.println("数量："+list.size());
//		} catch (DocumentException e) {
//			e.printStackTrace();
//		}
	}
}
